import React, { useEffect, useRef, useState } from 'react';
import ProForm, { ModalForm, ProFormText, ProFormDateTimePicker, ProFormSelect, ProFormDigit } from '@ant-design/pro-form';
import { Form, FormInstance } from 'antd';
import { getWorkerListByPage } from '@/services/human-resources/api';
import { showMsg, formatDate, diffDays, formatMoney, isNull, getDateValue, MsgType } from '@/utils/utils';
import { OptType } from '@/utils/constants';
import moment from 'moment';

const ServiceForm: React.FC<any> = (props) => {
  const { 
    handleModalVisible, 
    handleAdd, 
    actionRef, 
    record = {},
    optType,
    serviceId,
    serviceType,
    onReload
  } = props;

  const formRef = useRef<FormInstance>();
  const [workerList, setWorkerList] = useState<HUMANRESOURCESAPI.WorkerItem[]>([]);
  const [day, setDay] = useState<number>();
  const [ygTotalPrice, setYgTotalPrice] = useState<number>(); // 预估服务费
  const [ygRecomPrice, setYgRecomPrice] = useState<number>(); // 预估介绍费
  const [totalPrice, setTotalPrice] = useState<number>(); // 核算服务费
  const [totalRecomPrice, setTotalRecomPrice] = useState<number>(); // 核算介绍费

  const getWorkerList = async () => {
    try {
      const params = {
        flag: '2', 
        current: 1, 
        service_type: serviceType,
        pageSize: 10000,
        job_status: 'Y',
      }
      // let begin_time = formRef.current?.getFieldValue('begin_time');
      // let end_time = formRef.current?.getFieldValue('end_time');
      // if (begin_time) {
      //   params.begin_time = formatDate(begin_time);
      // }
      // if (end_time) {
      //   params.end_time = formatDate(end_time);
      // }
      
      // if (!begin_time || !end_time) {
      //   return;
      // }
      const data = await getWorkerListByPage(params);
      setWorkerList(data.record_list || []);
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  useEffect(() => {
    getWorkerList();
    // if (optType === OptType.VIEW) {
    //   const params = {
    //     current: 1, 
    //     pageSize: 10000
    //   }
    //   getWorkerListByPage(params).then(res => {
    //     setWorkerList(res.record_list || []);
    //   });
    // }
  }, [optType]);

  const makePrice = () => {
    const end_time = formRef.current?.getFieldValue('end_time')
    const begin_time = formRef.current?.getFieldValue('begin_time');

    if (begin_time && end_time) {
      if (getDateValue(begin_time) > getDateValue(end_time)) {
        formRef.current?.setFieldsValue({
          end_time: null
        })
        showMsg('服务结束时间不能早于开始时间', MsgType.INFO);
        return;
      }
    }
    let d = diffDays(begin_time, end_time).toFixed(2)
    // 计算系统计算天数
    if (begin_time && end_time) {
      setDay(d);
    }
    // 核算天数
    const check_day = formRef.current?.getFieldValue('check_day') || 0;
    // 服务单价
    const service_price = formRef.current?.getFieldValue('service_price') || 0;
    // 介绍费
    const recom_price = formRef.current?.getFieldValue('recom_price') || 0;
    console.log('begin_time, end_time', check_day, service_price, recom_price, !isNull(check_day), !isNull(service_price), !isNull(recom_price))
    if (!isNull(d)) {
      setYgTotalPrice(parseFloat(service_price * d).toFixed(2));
      setYgRecomPrice(parseFloat(recom_price * d).toFixed(2));
    }
    // 计算核算服务费
    if (!isNull(check_day)) {
      if (!isNull(service_price)) {
        setTotalPrice(parseFloat(service_price * check_day).toFixed(2))
      }
      if (!isNull(recom_price)) {
        setTotalRecomPrice(parseFloat(check_day * recom_price).toFixed(2))
      }
    }
  }
  
  return <ModalForm
      title="新增/编辑服务记录"
      width="80%"
      visible
      modalProps={{
        maskClosable: false
      }}
      className="service-record-modal"
      layout="horizontal"
      formRef={formRef}
      onVisibleChange={handleModalVisible}
      onFinish={async (value) => {
        if (value.begin_time && value.end_time) {
          if (getDateValue(value.begin_time) > getDateValue(value.end_time)) {
            showMsg('服务结束时间不能早于开始时间', MsgType.INFO);
            return;
          }
        }

        const worker = workerList.find(item => item.worker_id === value.worker_id);
        value = Object.assign({}, value, {
          worker_no: worker?.worker_no,
          worker_name: worker?.worker_name,
          begin_time: formatDate(value.begin_time),
          end_time: formatDate(new Date()),
          day: 0,
          // check_total_price: String(totalPrice).replace(/\$\s?|(,*)/g, ''),
          // check_total_recom_price: String(totalRecomPrice).replace(/\$\s?|(,*)/g, '')
          check_day: day || 0,
          // total_service_price: ygTotalPrice,
          // check_total_price: ygTotalPrice,
          // total_recom_price: value.recomPrice,
          // check_total_recom_price: ygRecomPrice
          total_service_price: null,
          check_total_price: null,
          total_recom_price: null,
          check_total_recom_price: null,
        });
        console.log('value', value);
        // return;
        const success = await handleAdd(value as HUMANRESOURCESAPI.NursingItem);
        if (success) {
          handleModalVisible(false);
          actionRef.current?.reload();
          onReload();
        }
      }}
      submitter={{
        searchConfig: {
          resetText: '取消',
          submitText: '保存'
        },
        submitButtonProps: {
          style: {
            display: optType === OptType.VIEW ? 'none' : 'block'
          }
        }
      }}>
        <ProForm.Group style={{display: optType === OptType.VIEW ? 'block' : 'none'}}>
          <Form.Item label="服务单号">{serviceId}</Form.Item>
        </ProForm.Group>

        <ProForm.Group>
          <ProFormDateTimePicker
            rules={
              [
                {
                  required: true
                }
              ]
            }
            label="服务开始时间"
            width="md"
            name="begin_time"
            initialValue={record.begin_time}
            readonly={optType === OptType.VIEW}
            fieldProps={
              {
                showTime: { defaultValue: moment('00', 'HH:mm')},
                format: "YYYY-MM-DD HH:mm",
                onChange: () => {
                  // makePrice();
                  // getWorkerList();
                }
              }
            }
          />
          {/* <ProFormDateTimePicker
            rules={
              [
                {
                  required: true
                }
              ]
            }
            label="服务结束时间"
            width="md"
            name="end_time"
            initialValue={record.end_time}
            readonly={optType === OptType.VIEW}
            fieldProps={
              {
                // showTime: { defaultValue: moment('23:59:59', 'HH:mm:ss')},
                showTime: { defaultValue: moment('23', 'HH')},
                format: "YYYY-MM-DD HH",
                onChange: () => {
                  makePrice();
                  getWorkerList();
                }
              }
            }
          /> */}
        </ProForm.Group>

        <ProForm.Group>
          <ProFormSelect
            rules={
                [
                  {
                    required: true
                  }
                ]
              }
              label="护工信息"
              width="md"
              name="worker_id"
              readonly={optType === OptType.VIEW}
              fieldProps={{
                options: workerList.map(item => {
                  return {
                    label: item.worker_no + '-' + item.worker_name,
                    value: item.worker_id as string
                  }
                }),
                showSearch: true,
                onChange: (value) => {
                  const worker = workerList.find(item => item.worker_id === value);
                  formRef.current?.setFieldsValue({
                    mobile: worker?.mobile
                  })
                }
              }}
              
              initialValue={record.worker_id}
            />
            <ProFormText
              label="联系电话"
              width="md"
              name="mobile"
              initialValue={record.mobile}
              readonly={optType === OptType.VIEW}
            />
        </ProForm.Group>
        
        <ProForm.Group>
          {
            optType === OptType.VIEW ? <ProFormText
              label="服务单价"
              width="md"
              name="service_price"
              initialValue={record.service_price + ' 元/天'}
              readonly={optType === OptType.VIEW}
            /> : <div style={{display: 'flex', position: 'relative'}}>
                <ProFormDigit
                  label="服务单价"
                  rules={
                    [
                      {
                        required: true
                      }
                    ]
                  }
                  width="md"
                  name="service_price"
                  initialValue={record.service_price}
                  fieldProps={{
                    min: 0.01,
                    precision: 2,
                    // formatter: (value) => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ','),
                    onChange: () => makePrice(),
                  }}
                />
                <span className="suffix">元/天</span>
              </div>
          }
          {
            optType === OptType.VIEW ? <ProFormText
              label="服务单价"
              width="md"
              name="service_price"
              initialValue={record.service_price + ' 元/天'}
              readonly={optType === OptType.VIEW}
            /> : 
            <div style={{display: 'flex', position: 'relative'}}>
              <ProFormDigit
                label="介绍费"
                rules={
                  [
                    {
                      required: true
                    }
                  ]
                }
                width="md"
                name="recom_price"
                initialValue={record.recom_price}
                readonly={optType === OptType.VIEW}
                fieldProps={{
                  min: 0.01,
                  precision: 2,
                  suffix: '元/天',
                  onChange: () => makePrice()
                }}
              />
              <span className="suffix">元/天</span>
            </div> 
          }

        </ProForm.Group>
        
        <ProForm.Group>
          {/* <Form.Item label="系统计算天数">
            {record.day || day || 0} 天
          </Form.Item>
          <Form.Item label="预估服务费">
            { formatMoney(record.total_service_price || ygTotalPrice || 0, true)} 元
          </Form.Item>
          <Form.Item label="预估介绍费">
            { formatMoney(record.real_total_recom_price || ygRecomPrice || 0, true)} 元
          </Form.Item>
           */}
           
          {/* <ProFormText
            rules={
              [
                {
                  required: true
                }
              ]
            }
            label="核算天数"
            width="md"
            name="check_day"
            initialValue={record.check_day}
            readonly={optType === OptType.VIEW}
            fieldProps={{
              suffix: '天',
              min: 0.01,
              precision: 2,
              onChange: () => makePrice()
            }}
          /> */}
        </ProForm.Group>
       
        {/* <ProForm.Group>
          <Form.Item label="核算服务费">
            { formatMoney(record.check_total_price || totalPrice || 0, true)} 元
          </Form.Item>
          
          <Form.Item label="核算介绍费">
            { formatMoney(record.real_total_recom_price || totalRecomPrice || 0, true)} 元
          </Form.Item>
        </ProForm.Group> */}
      
    </ModalForm>
}
export default ServiceForm;
